package com.frame.management;
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.ArrayList;
import java.util.List;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.ListSelectionModel;
import javax.swing.table.DefaultTableModel;

import com.excel.Utils;
import com.excel.service.StudentService;
import com.excel.service.StudentServiceImpl;
import com.excel.student.Student;
//维护表格
public class MainSystem extends JFrame{

    /**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private DefaultTableModel tableModel;   //表格模型对象
    private JTable table;
    private JTextField aTextField;
    private JTextField bTextField;
    private JTextField cTextField;
    private StudentService service;
    
    
    private JTextField searchText;

    public static String [][]tableVales ;
    
    public MainSystem()
    {

        super();
    	setSize(800, 600);
		setLocation(400, 170);
        setTitle("*****欢迎登录宿舍安全卫生检查系统*****");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        String[] columnNames = {"学号","姓名","班级"};   //列名
        
        //得到student service，用来增删改查
        service = StudentServiceImpl.getInstance();
        //初始化Table的每行数据
        tableVales = new String[Utils.studentMap.keySet().size()][];
        List<String[]> list = new ArrayList<>();
        for (String key: Utils.studentMap.keySet()) {
			list.add(Utils.studentMap.get(key).toArray());
		}
        for (int i = 0; i < tableVales.length; i++) {
        	tableVales[i] = list.get(i);
		}
        
        
        tableModel = new DefaultTableModel(tableVales,columnNames);
        table = new JTable(tableModel);
        JScrollPane scrollPane = new JScrollPane(table);   //支持滚动
        getContentPane().add(scrollPane,BorderLayout.CENTER);
        //jdk1.6
        //排序:
        //table.setRowSorter(new TableRowSorter(tableModel));
        table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);  //table只能单选
        //单机选中每一行，数据填入到最下边
        table.addMouseListener(new MouseAdapter(){    //鼠标事件
            public void mouseClicked(MouseEvent e){
                int selectedRow = table.getSelectedRow(); //获得选中行索引
                Object oa = tableModel.getValueAt(selectedRow, 0);
                Object ob = tableModel.getValueAt(selectedRow, 1);
                Object oc= tableModel.getValueAt(selectedRow, 2);

                aTextField.setText(oa.toString());  //给文本框赋值
                bTextField.setText(ob.toString());
                cTextField.setText(oc.toString());

            }
        });
        
        scrollPane.setViewportView(table);
        final JPanel panel = new JPanel();
        getContentPane().add(panel,BorderLayout.SOUTH);
        panel.add(new JLabel("学号: "));
        aTextField = new JTextField("",10);
        panel.add(aTextField);
        
        panel.add(new JLabel("姓名: "));
        bTextField = new JTextField("",10);
        panel.add(bTextField);
        
        panel.add(new JLabel("班级: "));
        cTextField = new JTextField("",10);
        panel.add(cTextField);
        
        final JButton addButton = new JButton("添加");   //添加按钮
        addButton.addActionListener(new ActionListener(){//添加事件
            public void actionPerformed(ActionEvent e){
            	//判断学号必须为数字
            	try {
            		Integer.parseInt(aTextField.getText());
				} catch (Exception e2) {
            		JOptionPane.showMessageDialog(null, "学号必须为数字", "错误消息",JOptionPane.ERROR_MESSAGE);  
            		return;
				}
            	Student s = new Student();
            	s.setId(Integer.parseInt(aTextField.getText()));
            	s.setName(bTextField.getText());
            	s.setCla(cTextField.getText());
            	
            	//判断 名字，班级不能为空
            	if(s.getName() == null || "".equals(s.getName())){
            		JOptionPane.showMessageDialog(null, "名字不能为空", "错误消息",JOptionPane.ERROR_MESSAGE);  
            		return;
            	}else if(s.getCla() == null ||  "".equals(s.getCla())){
            		JOptionPane.showMessageDialog(null, "班级不能为空", "错误消息",JOptionPane.ERROR_MESSAGE);  
            		return;
            	}
            	
            	//判断学号不能已经存在
            	if(service.findById(s.getId()) != null){
            		System.out.println("该学号的学生已经存在");
            		JOptionPane.showMessageDialog(null, "该学号的学生已经存在", "错误消息",JOptionPane.ERROR_MESSAGE);  
            	}else{
            		//把添加的值放到table，同时调用API增加student
                    String []rowValues = {aTextField.getText(),bTextField.getText(),cTextField.getText()};
                    tableModel.addRow(rowValues);  //添加一行
                    service.addStudent(s);
            	}
            	

            }
        });
        panel.add(addButton);  
        
        final JButton updateButton = new JButton("修改");   //修改按钮
        updateButton.addActionListener(new ActionListener(){//添加事件
            public void actionPerformed(ActionEvent e){
                int selectedRow = table.getSelectedRow();//获得选中行的索引
                //是否存在选中行
				if (selectedRow != -1) {
	                String oa = (String)tableModel.getValueAt(selectedRow, 0);
	                //选中行
	                if(!oa.equals(aTextField.getText())){
	            		JOptionPane.showMessageDialog(null, "学号不允许修改", "错误消息",JOptionPane.ERROR_MESSAGE);  
	            		return;
	                }
					
					
					// 修改指定的值：
					// tableModel.setValueAt(aTextField.getText(), selectedRow,0);
					tableModel.setValueAt(bTextField.getText(), selectedRow, 1);
					tableModel.setValueAt(cTextField.getText(), selectedRow, 2);

					Student s = new Student();
					s.setId(Integer.parseInt(aTextField.getText()));
					s.setName(bTextField.getText());
					s.setCla(cTextField.getText());

					service.updateStudent(s);
				} else {
            		JOptionPane.showMessageDialog(null, "未选中任何行", "错误消息",JOptionPane.ERROR_MESSAGE);  
				}
            }
        });
        panel.add(updateButton);
        
        final JButton delButton = new JButton("删除");
        delButton.addActionListener(new ActionListener(){//添加事件
            public void actionPerformed(ActionEvent e){
				int selectedRow = table.getSelectedRow();// 获得选中行的索引
				// 存在选中行
				if (selectedRow != -1) {
					tableModel.removeRow(selectedRow); // 删除行
					service.deleteStudent(Integer.parseInt(aTextField.getText()));
				} else {
            		JOptionPane.showMessageDialog(null, "未选中任何行", "错误消息",JOptionPane.ERROR_MESSAGE);  
				}
            }
        });
        panel.add(delButton);
        
        
        final JPanel panel1 = new JPanel();
        getContentPane().add(panel1,BorderLayout.NORTH);
        panel1.add(new JLabel("请输入查询学号: ") ,BorderLayout.LINE_START);
        searchText = new JTextField("",10);
        panel1.add(searchText);
        final JButton searchButton = new JButton("查询");
        searchButton.addActionListener(new ActionListener(){//添加事件
            public void actionPerformed(ActionEvent e){
            	String key = searchText.getText();
            	if(key == null || "".equals(key)){
            		JOptionPane.showMessageDialog(null, "请输入学号", "错误消息",JOptionPane.ERROR_MESSAGE);  

            	}else{
            		StringBuffer sb = new StringBuffer();
            		sb.append("未查找到任何学生信息。");
            		for (int i = 0; i < tableVales.length; i++) {
            			String[] values = tableVales[i];
            			if(key.equals(values[0])){
            				sb = new StringBuffer();
            				sb.append("查找到对应的学生信息为：\n");
            				sb.append("学号:"+values[0]);
            				sb.append("\n");
            				sb.append("姓名："+values[1]);
            				sb.append("\n");
            				sb.append("班级："+values[2]);
            				break;
            			}
					}
            		
            		JOptionPane.showMessageDialog(null, sb.toString(), "查询结果",JOptionPane.INFORMATION_MESSAGE);  
				}

            }
        });
        panel1.add(searchButton);
        
    }
    
    

}